import { Component, ContentChild, ElementRef, EventEmitter, Injector, Input, OnDestroy, OnInit, Output, ViewChild, ViewEncapsulation } from '@angular/core';
import { ControlValueAccessor } from '@angular/forms';

import E from "wangeditor"
import hljs from 'highlight.js'
import "node_modules/highlight.js/styles/xcode.css"
import { HttpClient } from '@angular/common/http';
import { NzMessageService } from 'ng-zorro-antd/message';
import { environment } from 'src/base/environments/environment';
import { NodeListType, NodeType } from 'wangeditor/dist/text/getChildrenJSON';

@Component({
  selector: 'ngs-editor',
  templateUrl: './editor.html',
  styleUrls: [
    '../../../../../node_modules/highlight.js/styles/xcode.css'],
  encapsulation: ViewEncapsulation.None,
})
export class NgsEditor implements OnInit, ControlValueAccessor, OnDestroy {

  baseUrl = environment.host;

  @ViewChild("wang")
  editor!: ElementRef;

  @Input() value: string = '';

  @Input() height = 500;

  @Output() valueChange = new EventEmitter();


  html = '';
  menuKeys = "";
  children = "";
  wangEditor: E | undefined;
  protected http: HttpClient;
  constructor(
    protected injector: Injector,
    private message: NzMessageService
  ) {
    this.http = injector.get(HttpClient);
  }
  ngOnDestroy(): void {
    this.wangEditor?.destroy();
  }
  writeValue(obj: any): void {
    this.html = obj;
    this.wangEditor?.txt.html(this.html)
  }
  registerOnChange(fn: any): void {
  }
  registerOnTouched(fn: any): void {
  }

  getValue() {
    return this.wangEditor?.txt.html();
  }

  setValue(obj: any) {
    this.html = obj;
  }

  // getMenus(): string {
  //   let evenets: any = this.wangEditor?.txt.getJSON();

  //   let menus: Array<any> = [];
  //   let indexMenus: any = {};
  //   let indexLevel: number = 0;
  //   if (evenets) {
  //     evenets.forEach((item: any, index: number) => {

  //       if (item.tag.indexOf("h") != -1) {
  //         let title = "";
  //         // 获取标题
  //         if(item.children.length < 2){
  //           if(item.children[0].children){
  //             title = item.children[0].children[0]+"";
  //           }else{
  //             title = item.children[0]+"";
  //           }
  //         }else{
  //           let sTitle = "";
  //           item.children.forEach((titleItem: any, index: number) => {
  //             if(titleItem.tag == "strong"){
  //               sTitle = sTitle + titleItem.children[0];
  //             }
  //           })
  //           title = sTitle;
  //         }

  //         // 获取 标题level
  //         let level = parseInt(item.tag.toLowerCase().replace("h", ""));

  //         let id = "";
  //         item.attrs.forEach((item: any, index: number) => {
  //           id = item.name == "id"?item.value:"";
  //         })
  //         if (!id) {
  //           id = `menus_${index + 1}`;
  //           let idData = {
  //             name:'id',
  //             value:id
  //           }
  //           item.attrs.push(idData);
  //         }
  //         //设置html json
  //         let content = `<a href="#${id}">${title}</a>`

  //         //组装标题目录
  //         if (index == 0) {
  //           indexMenus.content = content;
  //           indexMenus.children = [];
  //           indexLevel = level;
  //         } else {
  //           let upEvent = evenets[index - 1];
  //           let upLevel = parseInt(upEvent.tag.toLowerCase().replace("h", ""));
  //           if (level > indexLevel) {
  //             let map: any = {};
  //             map.content = content;
  //             map.children = [];
  //             if (level > upLevel && indexMenus.length > 0) {
  //               indexMenus.children[indexMenus.length].children.push(map);
  //             } else {
  //               indexMenus.children.push(map);
  //             }
  //           } else {
  //             let map = JSON.parse(JSON.stringify(indexMenus));
  //             menus.push(map);
  //             indexMenus.content = content;
  //             indexMenus.children = [];
  //             indexLevel = level;
  //           }
  //         }

  //         if(index + 1 == evenets.length){
  //           menus.push(indexMenus);
  //         }
  //       }
  //     })
  //     this.wangEditor?.txt.setJSON(evenets);
  //   }
  //   return JSON.stringify(menus);
  // }

  getMenus(): string {
    let evenets: any = this.wangEditor?.txt.getJSON();

    let menus: Array<any> = [];
    if (evenets) {
      evenets.forEach((item: any, index: number) => {

        if (item.tag.indexOf("h") != -1) {
          let title = "";
          // 获取标题
          if (item.children.length < 2) {
            if (item.children[0].children) {
              title = item.children[0].children[0] + "";
            } else {
              title = item.children[0] + "";
            }
          } else {
            let sTitle = "";
            item.children.forEach((titleItem: any, index: number) => {
              if (titleItem.tag == "strong") {
                sTitle = sTitle + titleItem.children[0];
              }
            })
            title = sTitle;
          }

          // 获取 标题level
          let level = parseInt(item.tag.toLowerCase().replace("h", ""));

          let id = "";
          item.attrs.forEach((item: any, index: number) => {
            id = item.name == "id" ? item.value : "";
          })
          if (!id) {
            id = `menus_${index + 1}`;
            let idData = {
              name: 'id',
              value: id
            }
            item.attrs.push(idData);
          }
          //设置html json
          let content = `<a class="navto" navto="${id}">${title}</a>`

          //组装标题目录
          let map: any = {};
          map.content = content;
          map.level = level;
          menus.push(map);

        }
      })
      this.wangEditor?.txt.setJSON(evenets);
    }
    return JSON.stringify(menus);
  }

  // souece 原字符串 start 要截取的位置 newStr 要插入的字符
  insertStr(source: string, start: number, newStr: string): string {
    return source.slice(0, start) + newStr + source.slice(start)
  }

  ngOnInit(): void {
    setTimeout(() => {
      this.wangEditor = new E(this.editor.nativeElement)
      this.wangEditor.config.zIndex = 500;
      this.wangEditor.config.height = this.height;
      this.wangEditor.highlight = hljs;
      this.wangEditor.config.onchange = (html: any) => {
        this.html = html;
        this.valueChange.emit(html)
      }
      this.wangEditor.config.uploadImgServer = this.baseUrl + "/oss/api";
      this.wangEditor.config.uploadFileName = "file";
      this.wangEditor.config.customUploadImg = (files: any, insertFn: any) => {
        let file = files[0];
        if (file.type.indexOf("image") < 0) {
          this.message.warning("只能上传图片！");
          return;
        }
        if (((file.size / 1024) / 1024) > 2) {
          this.message.warning("图片大小不能大于2M！");
          return;
        }
        let formData = new FormData();
        formData.append("file", file);
        this.http.post(this.baseUrl + "/oss/api", formData).subscribe((res: any) => {
          if (res.url) {
            insertFn(res.url);
          }
        });
      }
      this.wangEditor.config.onchangeTimeout = 500;
      this.wangEditor.create();
      this.wangEditor.txt.html(this.html);
    }, 500);
  }

}